<template>
  <div class="assessment-container">
    <div class="assessment-header">
      <button class="back-button" @click="goBack">← 返回</button>
      <h1>{{ assessmentTitle }}</h1>
      <div class="progress-info">
        <span>第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ questions.length }} 题</span>
        <span>剩余时间: {{ minutes }}:{{ seconds }}</span>
      </div>
    </div>

    <div class="progress-bar">
      <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button class="retry-button" @click="fetchQuestions">重试</button>
    </div>

    <div v-else class="question-container">
      <div class="question-header">
        <h2>{{ currentQuestion.content }}</h2>
        <p class="dimension-tag">维度: {{ currentQuestion.dimension }}</p>
      </div>

      <div class="options-container">
        <div
          v-for="option in currentQuestion.options"
          :key="option.text"
          class="option-item"
          :class="{ selected: selectedOption === option.text || selectedOption === option.score || selectedOption === option.code }"
          @click="selectOption(option.text)"
        >
          <div class="option-radio">
            <div class="radio-inner" :class="{ filled: selectedOption === option.text || selectedOption === option.score || selectedOption === option.code }"></div>
          </div>
          <div class="option-text">
            <span class="option-score">{{ option.score || option.code }}</span>
            <span class="option-content">{{ option.text }}</span>
          </div>
        </div>
      </div>

      <div class="navigation-buttons">
        <button
          class="nav-button prev-button"
          :disabled="currentQuestionIndex === 0"
          @click="goToPreviousQuestion"
        >
          上一题
        </button>
        <button
          class="nav-button next-button"
          :disabled="!selectedOption"
          @click="goToNextQuestion"
        >
          {{ currentQuestionIndex === questions.length - 1 ? '提交测评' : '下一题' }}
        </button>
      </div>
    </div>

    <!-- 测评完成弹窗 -->
    <div v-if="showCompletionModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>测评完成！</h3>
        </div>
        <div class="modal-body">
          <p>恭喜您完成了本次测评！</p>
          <p class="score-summary">
            您的总分为: <strong>{{ totalScore }}</strong>
          </p>
        </div>
        <div class="modal-footer">
          <button class="view-result-button" @click="viewResult">查看结果</button>
          <button class="back-to-list-button" @click="backToList">返回测评列表</button>
        </div>
      </div>
    </div>
    
    <!-- 时间到弹窗 -->
    <div v-if="showTimeUpModal" class="modal-overlay">
      <div class="modal-content time-up-modal">
        <div class="modal-header">
          <h3>测评时间到！</h3>
        </div>
        <div class="modal-body">
          <p>很遗憾，您的测评时间已结束。</p>
          <p>系统将在3秒后自动返回测评列表页面。</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { questionAPI } from '@/utils/api'
import { resultAPI } from '@/utils/api'
import { useUserStore } from '@/stores/user'

export default {
  name: 'AssessmentView',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const userStore = useUserStore()
    
    const assessmentId = parseInt(route.params.id)
    const questions = ref([])
    const currentQuestionIndex = ref(0)
    const selectedOption = ref(null)
    const userAnswers = ref({})
    const loading = ref(true)
    const error = ref('')
    const showCompletionModal = ref(false)
    const totalScore = ref(0)
    const assessmentTitle = ref('')
    const totalSeconds = ref(20 * 60) // 20分钟转换为秒
    const timer = ref(null)
    const showTimeUpModal = ref(false)



    // 当前问题
    const currentQuestion = computed(() => {
      return questions.value[currentQuestionIndex.value] || {}
    })

    // 进度百分比
    const progressPercentage = computed(() => {
      if (questions.value.length === 0) return 0
      return ((currentQuestionIndex.value + 1) / questions.value.length) * 100
    })
    
    // 计算剩余分钟数
    const minutes = computed(() => {
      return Math.floor(totalSeconds.value / 60).toString().padStart(2, '0')
    })
    
    // 计算剩余秒数
    const seconds = computed(() => {
      return (totalSeconds.value % 60).toString().padStart(2, '0')
    })

    // 获取问题列表
    const fetchQuestions = async () => {
      loading.value = true
      error.value = ''
      try {
        // 尝试从API获取问题
        const response = await questionAPI.getQuestions(assessmentId)

        // 直接使用API返回的questions数组
        questions.value = response || []

        // 设置测评标题
        if (assessmentId === 1) {
          assessmentTitle.value = '中学生心理健康量表'
        } else {
          assessmentTitle.value = '心理测试题库'
        }

        // 初始化用户答案
        if (!userAnswers.value) {
          userAnswers.value = {}
        }

        // 如果当前问题已经有答案，加载它
        if (questions.value.length > 0 && userAnswers.value[questions.value[0].question_id]) {
          selectedOption.value = userAnswers.value[questions.value[0].question_id]
        } else {
          selectedOption.value = null
        }
        
        // 动态设置测评标题
        if (assessmentId === 1) {
          assessmentTitle.value = '中学生心理健康量表'
        } else if (assessmentId === 2) {
          assessmentTitle.value = '心理测试题库'
        } else if (assessmentId === 3) {
          assessmentTitle.value = '职业兴趣测评'
        } else if (assessmentId === 4) {
          assessmentTitle.value = '性格特质评估'
        } else if (assessmentId === 5) {
          assessmentTitle.value = '人格测试(MBTI)'
        } else {
          assessmentTitle.value = '心理测试题库'
        }
      } catch (err) {
        error.value = '加载问题失败'
        console.error('Failed to fetch questions:', err)
      } finally {
        loading.value = false
      }
    }

    // 选择答案
    const selectOption = (optionIdentifier) => {
      selectedOption.value = optionIdentifier
      userAnswers.value[currentQuestion.value.question_id] = optionIdentifier
    }

    // 上一题
    const goToPreviousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
        // 加载之前的答案
        selectedOption.value = userAnswers.value[currentQuestion.value.question_id] || null
      }
    }

    // 下一题或提交
    const goToNextQuestion = async () => {
      if (currentQuestionIndex.value === questions.value.length - 1) {
        // 提交测评
        await submitAssessment()
      } else {
        currentQuestionIndex.value++
        // 加载之前的答案或重置
        selectedOption.value = userAnswers.value[currentQuestion.value.question_id] || null
      }
    }

    // 提交测评
    const submitAssessment = async () => {
      loading.value = true
      try {
        // 构建提交数据
        const submitData = {
          assessmentId: assessmentId,
          answers: userAnswers.value
        }

        // 提交结果到后端获取得分和报告
        const response = await questionAPI.submitAnswers(submitData)
        
        if (response && response.data) {
          // 计算总分（将所有维度的得分相加）
          const dimensionScores = response.data.scores
          let calculatedScore = 0
          for (const dimension in dimensionScores) {
            calculatedScore += parseFloat(dimensionScores[dimension])
          }
          
          // 更新setup中定义的totalScore ref变量
          totalScore.value = calculatedScore
          
          // 优先从userStore获取用户ID，如果没有则从localStorage获取，最后才使用默认值
          const userId = userStore.user?.id || localStorage.getItem('userId') || 1
          
          console.log('当前用户ID:', userId)
          console.log('计算的总分:', totalScore.value)
          
          // 构建保存到结果表的数据
          const resultData = {
            user_id: userId,
            assessment_id: assessmentId,
            score: totalScore.value,
            answers: userAnswers.value
          }
          console.log('提交到后端的结果数据:', resultData)
          
          // 调用resultAPI保存结果到数据库
          try {
            const saveResponse = await resultAPI.createResult(resultData)
            
            console.log('保存结果到数据库的响应:', saveResponse)
            
            if (saveResponse && saveResponse.resultId) {
              const resultId = saveResponse.resultId
              
              console.log('成功保存结果，resultId:', resultId)
              
              // 存储resultId，用于后续查看结果
              localStorage.setItem('lastResultId', resultId)
            } else {
              console.error('保存结果失败：没有返回resultId', saveResponse)
              alert('测评结果保存失败，请联系管理员')
            }
          } catch (error) {
            console.error('保存结果到数据库时发生错误:', error)
            alert('测评结果保存失败，请联系管理员')
          }
          
          // 显示完成弹窗
          showCompletionModal.value = true
        } else {
          // 显示完成弹窗（即使提交失败，也让用户知道测评已完成）
          showCompletionModal.value = true
        }
      } catch (err) {
        console.error('Failed to submit assessment:', err)
        alert('提交测评结果失败，但您的测评已完成')
        // 即使提交失败，也显示完成弹窗
        showCompletionModal.value = true
      } finally {
        loading.value = false
      }
    }

    // 计算各维度得分（暂时注释，因为当前未使用）
    // const calculateDimensionsScore = () => {
    //   const dimensions = {}
    //
    //   questions.value.forEach((question) => {
    //     const answer = userAnswers.value[question.question_id]
    //     if (answer && question.dimension) {
    //       if (!dimensions[question.dimension]) {
    //         dimensions[question.dimension] = 0
    //       }
    //       dimensions[question.dimension] += parseInt(answer)
    //     }
    //   })
    //
    //   return dimensions
    // }

    // 查看结果
    const viewResult = () => {
      // 获取存储的resultId
      const resultId = localStorage.getItem('lastResultId')
      
      if (resultId) {
        // 跳转到结果详情页
        router.push(`/assessment/result/${resultId}`)
      } else {
        // 如果没有resultId，返回测评列表
        backToList()
      }
    }

    // 返回测评列表
    const backToList = () => {
      router.push('/assessment')
    }

    // 返回上一页
    const goBack = () => {
      if (currentQuestionIndex.value === 0) {
        router.push('/assessment')
      } else {
        goToPreviousQuestion()
      }
    }

    // 计时器逻辑
    const startTimer = () => {
      if (timer.value) {
        clearInterval(timer.value)
      }

      timer.value = setInterval(() => {
        if (totalSeconds.value > 0) {
          totalSeconds.value--
        } else {
          // 时间到，显示提示并跳转
          clearInterval(timer.value)
          showTimeUpModal.value = true
          // 3秒后自动跳转到测评列表页面
          setTimeout(() => {
            router.push('http://localhost:5173/assessment')
          }, 3000)
        }
      }, 1000) // 每秒更新一次
    }

    // 清理计时器
    const clearTimer = () => {
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
    }

    // 监听问题变化，更新计时器显示 - 移除原有的估算逻辑，保持固定倒计时

    onMounted(() => {
      fetchQuestions()
      startTimer()
    })

    onBeforeUnmount(() => {
      clearTimer()
    })

    return {
      assessmentId,
      questions,
      currentQuestionIndex,
      selectedOption,
      userAnswers,
      loading,
      error,
      showCompletionModal,
      totalScore,
      assessmentTitle,
      totalSeconds,
      minutes,
      seconds,
      showTimeUpModal,
      currentQuestion,
      progressPercentage,
      fetchQuestions,
      selectOption,
      goToPreviousQuestion,
      goToNextQuestion,
      submitAssessment,
      viewResult,
      backToList,
      goBack,
    }
  },
}
</script>

<style scoped>
.assessment-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.assessment-header {
  text-align: center;
  margin-bottom: 20px;
}

.back-button {
  position: absolute;
  left: 20px;
  top: 20px;
  background: none;
  border: none;
  font-size: 16px;
  color: #61dafb;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(97, 218, 251, 0.1);
}

.assessment-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  max-width: 600px;
  margin: 0 auto;
  font-size: 14px;
  color: #666;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 4px;
  margin-bottom: 30px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) inset;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #61dafb 0%, #4fc0e8 100%);
  transition: width 0.3s ease;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(97, 218, 251, 0.3);
  border-top: 3px solid #61dafb;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.retry-button {
  background: #61dafb;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s ease;
}

.retry-button:hover {
  background: #4fc0e8;
}

.question-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.question-header {
  margin-bottom: 30px;
}

.question-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
  line-height: 1.5;
}

.dimension-tag {
  display: inline-block;
  background: rgba(97, 218, 251, 0.1);
  color: #61dafb;
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
}

.options-container {
  margin-bottom: 30px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-item:hover {
  border-color: #61dafb;
  background: rgba(97, 218, 251, 0.05);
}

.option-item.selected {
  border-color: #61dafb;
  background: rgba(97, 218, 251, 0.1);
}

.option-radio {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 2px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.option-item.selected .option-radio {
  border-color: #61dafb;
}

.radio-inner {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #61dafb;
  transform: scale(0);
  transition: transform 0.3s ease;
}

.option-item.selected .radio-inner.filled {
  transform: scale(1);
}

.option-text {
  display: flex;
  align-items: center;
  flex-grow: 1;
}

.option-score {
  font-weight: bold;
  color: #61dafb;
  margin-right: 10px;
  min-width: 20px;
}

.option-content {
  font-size: 16px;
  color: #333;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
}

.nav-button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.prev-button {
  background: #f0f0f0;
  color: #666;
}

.prev-button:hover:not(:disabled) {
  background: #e0e0e0;
}

.next-button {
  background: linear-gradient(135deg, #61dafb 0%, #4fc0e8 100%);
  color: white;
}

.next-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(97, 218, 251, 0.3);
}

.nav-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

/* 时间到弹窗样式 */
.time-up-modal .modal-header h3 {
  color: #ff6b6b;
}

.time-up-modal .modal-body p {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.6;
}

.time-up-modal .modal-body {
  margin-bottom: 0;
  padding-bottom: 20px;
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 40px;
  max-width: 500px;
  width: 90%;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}

.modal-header h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.modal-body {
  margin-bottom: 30px;
}

.modal-body p {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.score-summary {
  font-size: 18px !important;
  color: #333 !important;
  font-weight: bold;
}

.modal-footer {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.view-result-button,
.back-to-list-button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-result-button {
  background: linear-gradient(135deg, #61dafb 0%, #4fc0e8 100%);
  color: white;
  margin-bottom: 10px;
}

.view-result-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(97, 218, 251, 0.3);
}

.back-to-list-button {
  background: #f0f0f0;
  color: #666;
}

.back-to-list-button:hover {
  background: #e0e0e0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assessment-container {
    padding: 10px;
  }

  .back-button {
    left: 10px;
    top: 10px;
    padding: 6px 12px;
    font-size: 14px;
  }

  .assessment-header h1 {
    font-size: 24px;
    margin-top: 40px;
  }

  .progress-info {
    flex-direction: column;
    gap: 5px;
  }

  .question-container {
    padding: 20px;
  }

  .question-header h2 {
    font-size: 20px;
  }

  .option-item {
    padding: 12px;
  }

  .nav-button {
    padding: 10px 20px;
    font-size: 14px;
  }

  .modal-content {
    padding: 30px 20px;
  }
}
</style>
